package com.iwithlong.weixincustomhandler;

import com.iwithlong.entity.Activity;
import com.iwithlong.service.ActivityService;
import com.iwithlong.vo.ActivityVo;
import com.ktanx.platform.setting.kit.SettingKit;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiexiaohan on 2018/2/1.
 */
@Log4j
public class EventWeixinCustomHandler implements WeixinCustomHandler{
    @Value("${weburl:https://www.ichangbanmini.com}")
    private String webUrl;

    @Override
    public Map<String, Object> dealWithJsonRequest(Map<String, Object> map) {
        String event = String.valueOf(map.get("Event"));
        if(!StringUtils.equals("user_enter_tempsession",event)){
            return null;
        }
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        log.info("获取activityService");
        ActivityService activityService = (ActivityService) wac.getBean("activityService");
        log.info(activityService);
        Map<String,Object> result = new HashMap<>();
        result.put("touser",map.get("FromUserName"));
        String sessionFrom = String.valueOf(map.get("SessionFrom"));
        if(StringUtils.equals(sessionFrom,"enter")){
            result.put("msgtype","text");
            Map<String,String> text = new HashMap<>();
            String content = SettingKit.getValue("weixinAppWelcomeWords");
            if(StringUtils.isBlank(content)){
                return null;
            }
            text.put("content",content);
            result.put("text",text);
        }else {
            ActivityVo activity = activityService.findById(Long.valueOf(sessionFrom));
            if(activity==null){
                result.put("msgtype","text");
                Map<String,String> text = new HashMap<>();
                text.put("content","该活动不存在");
                result.put("text",text);
                return result;
            }
            String picUrl = activityService.findActivityFirstPicUrl(activity.getActivityId());
            result.put("msgtype","link");
            Map<String,String> link = new HashMap<>();
            link.put("title",activity.getName()+"购票");
            link.put("description",activity.getBrief());
            log.info("webUrl:"+webUrl);
            link.put("url",webUrl+"/upload/get/image.json?url="+picUrl);
            link.put("thumb_url",activity.getTicketUrl());
            result.put("link",link);
        }
        return result;
    }
}
